<template>
  <div class="product-detail">
    <!-- 商品图片轮播 -->
    <van-swipe class="product-swipe" :autoplay="3000" indicator-color="white">
      <van-swipe-item v-for="(image, index) in product.images" :key="index">
        <img :src="image" class="product-image" />
      </van-swipe-item>
    </van-swipe>

    <!-- 商品基本信息 -->
    <div class="product-info">
      <div class="price-section">
        <span class="current-price">¥{{ product.price }}</span>
        <span class="original-price" v-if="product.originalPrice">¥{{ product.originalPrice }}</span>
        <van-tag type="danger" v-if="product.discount">{{ product.discount }}折</van-tag>
      </div>

      <h2 class="product-title">{{ product.title }}</h2>
      <p class="product-desc">{{ product.description }}</p>

      <div class="meta-info">
        <span>销量: {{ product.sales }}</span>
        <span>库存: {{ product.stock }}</span>
        <span>收藏: {{ product.favorites }}</span>
      </div>
    </div>

    <!-- 商品规格选择 -->
    <van-cell title="选择规格" is-link @click="showSpecPopup = true" />

    <!-- 评论区域 -->
    <div class="comment-section">
      <div class="section-header">
        <h3>商品评价</h3>
        <span class="comment-more" @click="viewAllComments">
          查看全部 {{ comments.total }} 条
          <van-icon name="arrow" />
        </span>
      </div>

      <div class="comment-stats">
        <div class="rating-overview">
          <span class="rating-score">{{ comments.averageRating }}</span>
          <span class="rating-text">综合评分</span>
        </div>
        <div class="rating-bars">
          <div class="rating-bar" v-for="(count, index) in comments.ratingDistribution" :key="index">
            <span class="rating-star">{{ 5 - index }}星</span>
            <van-progress :percentage="(count / comments.total) * 100" :show-pivot="false" />
            <span class="rating-count">{{ count }}</span>
          </div>
        </div>
      </div>

      <!-- 评论列表 -->
      <div class="comment-list">
        <div class="comment-item" v-for="comment in comments.list" :key="comment.id">
          <div class="comment-header">
            <div class="user-info">
              <img :src="comment.user.avatar" class="user-avatar" />
              <span class="user-name">{{ comment.user.name }}</span>
            </div>
            <span class="comment-time">{{ comment.time }}</span>
          </div>

          <div class="comment-rating">
            <van-rate v-model="comment.rating" readonly size="14" />
          </div>

          <p class="comment-content">{{ comment.content }}</p>

          <!-- 评论图片 -->
          <div class="comment-images" v-if="comment.images && comment.images.length">
            <img
                v-for="(img, imgIndex) in comment.images"
                :key="imgIndex"
                :src="img"
                class="comment-image"
                @click="previewImage(comment.images, imgIndex)"
            />
          </div>

          <!-- 评论回复 -->
          <div class="comment-reply" v-if="comment.reply">
            <span class="reply-label">商家回复：</span>
            {{ comment.reply }}
          </div>

          <div class="comment-actions">
            <span class="action-item" @click="likeComment(comment)">
              <van-icon :name="comment.liked ? 'good-job' : 'good-job-o'" />
              {{ comment.likes }}
            </span>
            <span class="action-item" @click="showReplyInput(comment)">
              <van-icon name="comment-o" />
              回复
            </span>
          </div>

          <!-- 回复输入框 -->
          <div class="reply-input" v-if="activeReplyComment === comment.id">
            <van-field
                v-model="replyContent"
                placeholder="写下你的回复..."
                rows="1"
                autosize
                type="textarea"
            />
            <div class="reply-actions">
              <van-button size="small" @click="cancelReply">取消</van-button>
              <van-button type="primary" size="small" @click="submitReply(comment)">发送</van-button>
            </div>
          </div>
        </div>
      </div>

      <!-- 添加评论表单 -->
      <div class="add-comment-section">
        <h3>添加评论</h3>
        <div v-if="!isLoggedIn" class="login-prompt">
          <p>请先登录后评论</p>
          <van-button type="primary" @click="goToLogin">立即登录</van-button>
        </div>
        <div v-else>
          <van-form @submit="onSubmitComment">
            <van-field
                v-model="commentForm.content"
                rows="2"
                autosize
                label="评论内容"
                type="textarea"
                placeholder="请输入评论内容"
                :rules="[{ required: true, message: '请输入评论内容' }]"
            />
            <van-field name="rating" label="评分">
              <template #input>
                <van-rate v-model="commentForm.rating" />
              </template>
            </van-field>
            <div style="margin: 16px;">
              <van-button round block type="primary" native-type="submit">
                提交评论
              </van-button>
            </div>
          </van-form>
        </div>
      </div>
    </div>

    <!-- 商品详情区域 -->
    <div class="detail-section">
      <h3>商品详情</h3>
      <div class="detail-content">
        <img
            v-for="(img, index) in product.detailImages"
            :key="index"
            :src="img"
            class="detail-image"
        />
      </div>
    </div>

    <!-- 底部操作栏 -->
    <van-action-bar>
      <van-action-bar-icon icon="chat-o" text="客服" @click="onClickService" />
      <van-action-bar-icon icon="cart-o" text="购物车" :badge="cartCount" @click="onClickCart" />
      <van-action-bar-icon
          icon="star"
          :text="favorited ? '已收藏' : '收藏'"
          :color="favorited ? '#ff5000' : ''"
          @click="toggleFavorite"
      />
      <van-action-bar-button type="warning" text="加入购物车" @click="addToCart" />
      <van-action-bar-button type="danger" text="立即购买" @click="buyNow" />
    </van-action-bar>

    <!-- 规格选择弹出层 -->
    <van-popup
        v-model:show="showSpecPopup"
        position="bottom"
        round
        :style="{ height: '70%' }"
    >
      <div class="spec-popup">
        <div class="popup-header">
          <img :src="product.images[0]" class="popup-product-image" />
          <div class="popup-price-info">
            <div class="current-price">¥{{ product.price }}</div>
            <div class="stock">库存: {{ product.stock }}件</div>
            <div class="selected-spec">已选: {{ getSelectedSpecsText() }}</div>
          <van-icon name="cross" class="close-icon" @click="showSpecPopup = false" />
        </div>

        <div class="spec-content">
          <!-- 规格选项 -->
          <div class="spec-group" v-for="spec in specifications" :key="spec.name">
            <h4>{{ spec.name }}</h4>
            <div class="spec-options">
              <van-button
                  v-for="option in spec.options"
                  :key="option.value"
                  :type="selectedSpecs[spec.name] === option.value ? 'primary' : 'default'"
                  size="small"
                  @click="selectSpec(spec.name, option.value)"
                  :disabled="option.disabled"
              >
                {{ option.label }}
              </van-button>
            </div>
          </div>

          <!-- 数量选择 -->
          <div class="quantity-selector">
            <h4>数量</h4>
            <van-stepper v-model="quantity" :max="product.stock" />
          </div>
        </div>

        <div class="popup-footer">
          <van-button
              type="primary"
              block
              @click="confirmSelection"
              :disabled="!isAllSpecsSelected"
          >
            {{ mode === 'cart' ? '加入购物车' : '立即购买' }}
          </van-button>
        </div>
      </div>
      </div>
    </van-popup>

    <!-- 图片预览 -->
    <van-image-preview
        v-model:show="showImagePreview"
        :images="previewImages"
        :start-position="previewIndex"
    />
  </div>
</template>

<script setup>
import { ref, reactive, computed, onMounted } from 'vue'
import { showToast, showConfirmDialog } from 'vant'
import axios from '../utils/axios.ts'
import { useRoute, useRouter } from 'vue-router'

const route = useRoute()
const router = useRouter()

// 添加用户信息相关数据
const isLoggedIn = ref(false);
const userInfo = reactive({
  mobile: '',
  token: ''
});

// 检查登录状态
const checkLoginStatus = () => {
  const token = sessionStorage.getItem('token');
  console.log('检查登录状态，token:', token);

  if (token) {
    isLoggedIn.value = true;
    userInfo.token = token;
    // 这里可以从token中解析用户信息，或者发请求获取用户信息
    // 暂时使用默认值
    userInfo.mobile = '138****8888';
    console.log('用户已登录');
  } else {
    isLoggedIn.value = false;
    userInfo.mobile = '';
    userInfo.token = '';
    console.log('用户未登录');
  }
};

// 登录跳转
const goToLogin = () => {
  router.push('/login');
};

// 商品数据
const product = reactive({
  id: null,
  title: '',
  description: '',
  price: 0,
  originalPrice: null,
  discount: null,
  sales: 0,
  stock: 0,
  favorites: 0,
  images: [],
  detailImages: []
})

// 评论数据
const comments = reactive({
  total: 0,
  averageRating: 0,
  ratingDistribution: [0, 0, 0, 0, 0],
  list: []
})

// 评论表单
const commentForm = reactive({
  content: '',
  rating: 5
})

// 购物车数量
const cartCount = ref(3)
// 是否已收藏
const favorited = ref(false)
// 是否显示规格选择弹出层
const showSpecPopup = ref(false)
// 购买数量
const quantity = ref(1)
// 当前模式（加入购物车或立即购买）
const mode = ref('cart')
// 当前激活的回复评论ID
const activeReplyComment = ref(null)
// 回复内容
const replyContent = ref('')
// 图片预览相关
const showImagePreview = ref(false)
const previewImages = ref([])
const previewIndex = ref(0)

// 规格数据
const specifications = reactive([
  {
    name: '颜色',
    options: [
      { label: '红色', value: 'red', disabled: false },
      { label: '蓝色', value: 'blue', disabled: false },
      { label: '绿色', value: 'green', disabled: true }
    ]
  },
  {
    name: '尺码',
    options: [
      { label: 'S', value: 's', disabled: false },
      { label: 'M', value: 'm', disabled: false },
      { label: 'L', value: 'l', disabled: false },
      { label: 'XL', value: 'xl', disabled: true }
    ]
  }
])

// 已选规格
const selectedSpecs = reactive({
  颜色: '',
  尺码: ''
})

// 检查是否所有规格都已选择
const isAllSpecsSelected = computed(() => {
  return Object.values(selectedSpecs).every(value => value !== '')
})

// 获取已选规格文本
const getSelectedSpecsText = () => {
  return Object.values(selectedSpecs).filter(v => v).join('，') || '请选择规格'
}

// 选择规格
const selectSpec = (specName, specValue) => {
  selectedSpecs[specName] = selectedSpecs[specName] === specValue ? '' : specValue
}

// 点击客服
const onClickService = () => {
  showToast('客服功能即将上线')
}

// 点击购物车
const onClickCart = () => {
  showToast('跳转到购物车')
}

// 切换收藏状态
const toggleFavorite = () => {
  favorited.value = !favorited.value
  showToast(favorited.value ? '已收藏' : '已取消收藏')
}

// 加入购物车
const addToCart = () => {
  mode.value = 'cart'
  showSpecPopup.value = true
}

// 立即购买
const buyNow = () => {
  mode.value = 'buy'
  showSpecPopup.value = true
}

// 确认选择
const confirmSelection = () => {
  if (!isAllSpecsSelected.value) {
    showToast('请选择完整规格')
    return
  }

  showSpecPopup.value = false

  if (mode.value === 'cart') {
    cartCount.value += quantity.value
    showToast(`已加入购物车 ${quantity.value} 件`)
  } else {
    showConfirmDialog({
      title: '确认购买',
      message: `确认购买 ${quantity.value} 件商品？`
    }).then(() => {
      showToast('购买成功')
    })
  }

  // 重置数量
  quantity.value = 1
}

// 查看所有评论
const viewAllComments = () => {
  showToast('查看所有评论')
}

// 点赞评论
const likeComment = (comment) => {
  comment.liked = !comment.liked
  comment.likes += comment.liked ? 1 : -1
  showToast(comment.liked ? '已点赞' : '已取消点赞')
}

// 显示回复输入框
const showReplyInput = (comment) => {
  activeReplyComment.value = comment.id
  replyContent.value = ''
}

// 取消回复
const cancelReply = () => {
  activeReplyComment.value = null
  replyContent.value = ''
}

// 提交回复
const submitReply = (comment) => {
  if (!replyContent.value.trim()) {
    showToast('请输入回复内容')
    return
  }

  // 这里应该是调用API提交回复
  axios.post(`/api/`)

  showToast('回复成功')
  activeReplyComment.value = null
  replyContent.value = ''
}

// 预览图片
const previewImage = (images, index) => {
  previewImages.value = images
  previewIndex.value = index
  showImagePreview.value = true
}

// 获取商品详情
const fetchProductDetail = async (id) => {
  try {
    axios.get(`/api/getProduct?pid=${id}`)
        .then(res => {
          const data = res.data

          // 映射数据到组件
          product.id = data.pid
          product.title = data.pname
          product.description = data.pdesc
          product.price = data.price
          product.sales = data.sales || 0
          product.stock = data.stock || 0
          product.favorites = data.collections || 0

          // 处理图片
          product.images = [
            data.pimg1,
            data.pimg2,
            data.pimg3
          ].filter(img => img)

          // 处理详情图片
          product.detailImages = [
            data.pimg1,
            data.pimg2,
            data.pimg3
          ].filter(img => img)
        })

  } catch (error) {
    console.error('获取商品详情失败:', error)
    showToast('获取商品详情失败')
  }
}

const formatTime = (dateStr) => {
  if (!dateStr) return '';
  const date = new Date(dateStr);
  return date.toLocaleDateString();
};

// 获取评论数据
const fetchComments = async (productId) => {
  try {
    const res = await axios.get(`/api/getGoodCom`, { params: { pid: productId } });
    const data = res.data;

    // 获取原始评论列表
    const commentList = data.data || data.records || [];

    // 计算总条数
    comments.total = commentList.length;

    // 计算平均评分
    const totalRating = commentList.reduce((sum, item) => sum + (item.rating || 0), 0);
    comments.averageRating = commentList.length > 0 ? (totalRating / commentList.length).toFixed(1) : 0;

    // 计算星级分布（5星到1星）
    comments.ratingDistribution = [0, 0, 0, 0, 0]; // [5星, 4星, 3星, 2星, 1星]
    commentList.forEach(comment => {
      const rating = comment.rating || 0;
      const ratingIndex = 5 - rating; // rating=5 -> index=0, rating=1 -> index=4
      if (ratingIndex >= 0 && ratingIndex < 5) {
        comments.ratingDistribution[ratingIndex]++;
      }
    });

    // 处理评论列表
    comments.list = commentList.map(comment => ({
      id: comment.id || comment.pid,
      content: comment.context || comment.content || '', // 修复字段名问题
      rating: comment.rating || 0,
      time: formatTime(comment.createAt || comment.created_at || comment.time),
      user: {
        ...comment.user,
        name: comment.user?.mobile || comment.user?.name || comment.user?.nickname || '匿名用户',
        avatar: comment.user?.avatar || 'https://img.yzcdn.cn/vant/cat.jpeg'
      },
      likes: comment.likes || 0,
      liked: false,
      reply: comment.reply || null,
      images: (comment.images || []).filter(img => img) // 过滤空图片
    }));

    console.log('评论数据已加载:', comments.list);
  } catch (error) {
    console.error('获取评论失败:', error);
    showToast('获取评论失败');
  }
}

// 提交评论
const onSubmitComment = () => {
  if (!isLoggedIn.value) {
    showToast('请先登录');
    return;
  }

  // 验证 token 是否存在
  const token = sessionStorage.getItem('token');
  console.log('当前 token:', token);
  console.log('用户信息:', userInfo);

  if (!token) {
    showToast('未找到用户凭证，请重新登录');
    return;
  }

  const formData = {
    pid: product.id,
    context: commentForm.content,
    rating: commentForm.rating,
    // 使用正确的用户对象结构
    user: {
      mobile: token // 假设token就是用户ID
    }
  };

  console.log('提交评论数据:', formData);

  axios.post('/api/comitComment', formData)
    .then(response => {
      console.log('评论提交响应:', response);
      if (response.data.code === 200) {
        showToast('评论提交成功');
        // 重置表单
        commentForm.content = '';
        commentForm.rating = 5;
        // 重新加载评论
        fetchComments(product.id);
      } else {
        showToast(response.data.msg || '评论提交失败');
      }
    })
    .catch(error => {
      console.error('评论提交失败:', error);
      console.log('提交的数据:', formData);
      showToast('评论提交失败: ' + (error.message || '网络错误'));
    });
};

// 页面加载时获取数据
onMounted(() => {
  checkLoginStatus();
  const productId = route.params.id
  if (productId) {
    console.log('开始加载商品详情...', productId);
    fetchProductDetail(productId)
    console.log('开始加载评论...');
    fetchComments(productId)
  }
})

</script>

<style scoped>
.product-detail {
  padding-bottom: 50px;
  background-color: #f7f8fa;
}

.product-swipe {
  height: 375px;
}

.product-image {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.product-info {
  padding: 16px;
  background: white;
  margin-bottom: 10px;
}

.price-section {
  display: flex;
  align-items: center;
  margin-bottom: 10px;
}

.current-price {
  font-size: 24px;
  font-weight: bold;
  color: #ff5000;
  margin-right: 10px;
}

.original-price {
  font-size: 14px;
  color: #999;
  text-decoration: line-through;
  margin-right: 10px;
}

.product-title {
  font-size: 16px;
  font-weight: normal;
  margin: 0 0 10px 0;
  line-height: 1.4;
}

.product-desc {
  font-size: 14px;
  color: #666;
  margin: 0 0 15px 0;
  line-height: 1.5;
}

.meta-info {
  display: flex;
  justify-content: space-between;
  font-size: 12px;
  color: #999;
}

/* 评论区域样式 */
.comment-section {
  background: white;
  padding: 16px;
  margin-bottom: 10px;
}

.section-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 16px;
}

.section-header h3 {
  margin: 0;
  font-size: 16px;
  font-weight: bold;
}

.comment-more {
  font-size: 12px;
  color: #999;
  display: flex;
  align-items: center;
}

.comment-stats {
  display: flex;
  align-items: center;
  padding: 16px 0;
  border-bottom: 1px solid #eee;
  margin-bottom: 16px;
}

.rating-overview {
  text-align: center;
  margin-right: 20px;
  min-width: 60px;
}

.rating-score {
  display: block;
  font-size: 24px;
  font-weight: bold;
  color: #ff5000;
}

.rating-text {
  font-size: 12px;
  color: #666;
}

.rating-bars {
  flex: 1;
}

.rating-bar {
  display: flex;
  align-items: center;
  margin-bottom: 8px;
}

.rating-star {
  width: 30px;
  font-size: 12px;
  color: #666;
}

.rating-count {
  width: 30px;
  text-align: right;
  font-size: 12px;
  color: #999;
}

:deep(.van-progress) {
  flex: 1;
  margin: 0 8px;
}

.comment-item {
  padding: 16px 0;
  border-bottom: 1px solid #f5f5f5;
}

.comment-item:last-child {
  border-bottom: none;
}

.comment-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 8px;
}

.user-info {
  display: flex;
  align-items: center;
}

.user-avatar {
  width: 24px;
  height: 24px;
  border-radius: 50%;
  margin-right: 8px;
}

.user-name {
  font-size: 14px;
  color: #333;
}

.comment-time {
  font-size: 12px;
  color: #999;
}

.comment-rating {
  margin-bottom: 8px;
}

.comment-content {
  font-size: 14px;
  line-height: 1.5;
  color: #333;
  margin-bottom: 12px;
}

.comment-images {
  display: flex;
  gap: 8px;
  margin-bottom: 12px;
}

.comment-image {
  width: 80px;
  height: 80px;
  border-radius: 4px;
  object-fit: cover;
}

.comment-reply {
  background: #f5f5f5;
  padding: 12px;
  border-radius: 4px;
  margin-bottom: 12px;
  font-size: 13px;
  line-height: 1.4;
}

.reply-label {
  color: #ff5000;
  font-weight: 500;
}

.comment-actions {
  display: flex;
  gap: 16px;
}

.action-item {
  display: flex;
  align-items: center;
  gap: 4px;
  font-size: 12px;
  color: #999;
}

.reply-input {
  margin-top: 12px;
  border: 1px solid #eee;
  border-radius: 4px;
  overflow: hidden;
}

.reply-actions {
  display: flex;
  justify-content: flex-end;
  gap: 8px;
  padding: 8px;
  background: #fafafa;
}

.add-comment-section {
  margin-top: 20px;
  padding-top: 20px;
  border-top: 1px solid #eee;
}

.login-prompt {
  text-align: center;
  padding: 20px 0;
}

.login-prompt p {
  margin-bottom: 15px;
  color: #666;
}

.detail-section {
  padding: 16px;
  background: white;
  margin-bottom: 10px;
}

.detail-section h3 {
  margin: 0 0 12px 0;
  font-size: 16px;
  font-weight: bold;
}

.detail-image {
  width: 100%;
  margin-bottom: 10px;
}

/* 规格弹出层样式 */
.spec-popup {
  display: flex;
  flex-direction: column;
  height: 100%;
}

.popup-header {
  display: flex;
  padding: 16px;
  position: relative;
  border-bottom: 1px solid #eee;
}

.popup-product-image {
  width: 80px;
  height: 80px;
  border-radius: 4px;
  object-fit: cover;
}

.popup-price-info {
  flex: 1;
  margin-left: 12px;
}

.popup-price-info .current-price {
  font-size: 18px;
}
</style>